import fetch from 'node-fetch';

const voiceAPI = 'http://frp-add.top:52956/';
const defaultSpeaker = 'default'; // 设置默认语音角色

async function synthesizeVoice(text, speaker = defaultSpeaker, speed = 1.0) {
    const url = `${voiceAPI}tts?text=${encodeURIComponent(text)}&speaker=${speaker}&speed=${speed}`;
    console.log('Generated URL:', url); // 使用 console.log 进行日志记录
    return url;
}

class Voice {
    static async sendVoice(e, text, speaker = defaultSpeaker, speed = 1.0) {
        try {
            const url = await synthesizeVoice(text, speaker, speed);
            await e.reply(segment.record(url));
        } catch (error) {
            console.error('Error in sendVoice:', error);
        }
    }
}

function getRandomMessage(messages) {
    return messages[Math.floor(Math.random() * messages.length)];
}

async function getCurrentSpeaker(key, defaultSpeaker) {
    const speaker = await redis.get(key);
    return speaker || defaultSpeaker;
}

class Newcomer extends plugin {
    constructor() {
        super({
            name: '欢迎新人',
            dsc: '新人入群欢迎',
            event: 'notice.group.increase',
        });
    }

    async accept(e) {
        if (e.user_id === e.self_id) return;

        const welcomeMessages = [
            '欢迎新人！',
            '欢迎加入我们的群组！',
            '很高兴见到你，欢迎！',
            '新人报到，大家欢迎！',
            '希望你在这里玩得开心！'
        ];
        const welcomeText = getRandomMessage(welcomeMessages);
        const cooldown = 30;
        const key = `Yz:newcomers:${e.group_id}`;

        if (await redis.get(key)) return;
        await redis.set(key, '1', { EX: cooldown });

        const speakerKey = 'newcomer_speaker';
        const speaker = await getCurrentSpeaker(speakerKey, 'welcome_speaker'); // 获取当前迎新语音角色
        await Voice.sendVoice(e, welcomeText, speaker);
    }
}

class OutNotice extends plugin {
    constructor() {
        super({
            name: '退群通知',
            dsc: 'xx退群了',
            event: 'notice.group.decrease'
        });
    }

    async accept(e) {
        if (e.user_id === e.self_id) return;

        const name = e.member?.card || e.member?.nickname || e.user_id;
        const leaveMessages = [
            `${name} 退群了`,
            `${name} 离开了我们的群组`,
            `${name} 再见，希望以后还能见到你`,
            `${name} 永别了`,
            `${name} 离开了，希望他一切顺利`
        ];
        const leaveText = getRandomMessage(leaveMessages);

        const speakerKey = 'outnotice_speaker';
        const speaker = await getCurrentSpeaker(speakerKey, 'default_goodbye_speaker'); // 获取当前退群通知语音角色，默认值改为default_goodbye_speaker
        await Voice.sendVoice(e, leaveText, speaker);
    }
}

class ModifySpeaker extends plugin {
    constructor() {
        super({
            name: '修改语音角色',
            dsc: '修改进群和退群的语音角色',
            event: 'message',
            priority: 5000,
            rule: [
                {
                    reg: '^#设置进群角色 .+$',
                    fnc: 'setNewcomerSpeaker'
                },
                {
                    reg: '^#设置退群角色 .+$',
                    fnc: 'setOutNoticeSpeaker'
                }
            ]
        });
    }

    async setNewcomerSpeaker(e) {
        const speaker = e.msg.replace(/^#设置进群角色 /, '').trim();
        try {
            await redis.set('newcomer_speaker', speaker);
            await e.reply(`迎新语音角色已成功设置为：${speaker}`);
        } catch (error) {
            console.error('Error setting newcomer speaker:', error);
            await e.reply('设置迎新语音角色失败，请稍后再试。');
        }
    }

    async setOutNoticeSpeaker(e) {
        const speaker = e.msg.replace(/^#设置退群角色 /, '').trim();
        try {
            await redis.set('outnotice_speaker', speaker);
            await e.reply(`退群通知语音角色已成功设置为：${speaker}`);
        } catch (error) {
            console.error('Error setting out notice speaker:', error);
            await e.reply('设置退群通知语音角色失败，请稍后再试。');
        }
    }
}

export { Newcomer, OutNotice, ModifySpeaker };
